﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.SessionState; //支持session必须的引用

using Skyworth.CRM.Common;
using Skyworth.CRM.Service.IBLL;

namespace Skyworth.CRM.Web.Service
{
    /// <summary>
    /// Login 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class Login : IHttpHandler, IRequiresSessionState
    {
        IUserBLL roleBLL = IocContainer.Instance.Resolve<IUserBLL>();
        IModulesBLL moduleBLL = IocContainer.Instance.Resolve<IModulesBLL>();
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string result = "";
            try
            {
                string userName = context.Request["UserName"];
                string password = context.Request["Password"];
                string verifyCode = context.Request["VerifyCode"];
                if (context.Request.Cookies["VerifyCode"] == null)
                {
                    // 您的浏览器设置已被禁用Cookies，您必须设置浏览器允许使用Cookies选项后才能使用本系统                
                    result = "3";
                }
                else if (String.Compare(context.Request.Cookies["VerifyCode"].Value, verifyCode.ToUpper(), true) == 0)
                {
                    int userId = -1;
                    int individualId = -1;
                    int userType = 1;
                    if (roleBLL.Exists(userName, Encrypt.MD5(password, 32), out userId, out individualId, out userType))
                    {
                        // 登录成功后保存信息
                        HttpContext.Current.Session["UserID"] = userId;
                        HttpContext.Current.Session["IndividualId"] = individualId;
                        HttpContext.Current.Session["UserType"] = userType;
                        HttpContext.Current.Session["UserName"] = userName;
                        HttpContext.Current.Session["FuncModelList"] = moduleBLL.GetModuleFunc(userId);
                        // 登录成功
                        result = "1";
                    }
                    else
                    {
                        // 用户名或密码错误
                        result = "0";
                    }
                }
                else
                {
                    // 验证码错误
                    result = "2";
                }
            }
            catch (Exception ex)
            {
                // 程序错误
                result = "4";
                Logger.Instance.Error(ex.Message);
            }
            context.Response.Write(result);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}